local extension = Package("joy_sp")
extension.extensionName = "joy"

Fk:loadTranslationTable{
  ["joy_sp"] = "欢乐-SP",
  ["joysp"] = "欢乐SP",
}

local U = require "packages/utility/utility"

local joysp__zhangfei = General(extension, "joysp__zhangfei", "shu", 4)
local joysp__paoxiao = fk.CreateTargetModSkill{
  name = "joysp__paoxiao",
  frequency = Skill.Compulsory,
  bypass_times = function(self, player, skill, scope)
    return player:hasSkill(self) and skill.trueName == "slash_skill" and scope == Player.HistoryPhase
  end,
  bypass_distances = function(self, player, skill, scope)
    return player:hasSkill(self) and skill.trueName == "slash_skill"
  end,
}
local joysp__paoxiao_trigger = fk.CreateTriggerSkill{
  name = "#joysp__paoxiao_trigger",
  events = {fk.TargetSpecified},
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and target == player and data.card.trueName == "slash" then
      local times = #player.room.logic:getEventsOfScope(GameEvent.UseCard, 3, function(e)
        local use = e.data[1]
        return use.from == player.id and use.card.trueName == "slash"
      end, Player.HistoryTurn)
      return (times == 2 and data.firstTarget) or times > 2
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local times = #room.logic:getEventsOfScope(GameEvent.UseCard, 3, function(e)
      local use = e.data[1]
      return use.from == player.id and use.card.trueName == "slash"
    end, Player.HistoryTurn)
    if data.firstTarget then
      data.additionalDamage = (data.additionalDamage or 0) + 1
    end
    if times > 2 then
      data.disresponsive = true
      room:addPlayerMark(room:getPlayerById(data.to), fk.MarkArmorNullified)
      data.extra_data = data.extra_data or {}
      data.extra_data.joysp__paoxiao = data.extra_data.joysp__paoxiao or {}
      data.extra_data.joysp__paoxiao[tostring(data.to)] = (data.extra_data.joysp__paoxiao[tostring(data.to)] or 0) + 1
    end
  end,

  refresh_events = {fk.CardUseFinished},
  can_refresh = function(self, event, target, player, data)
    return data.extra_data and data.extra_data.joysp__paoxiao
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    for key, num in pairs(data.extra_data.joysp__paoxiao) do
      local p = room:getPlayerById(tonumber(key))
      if p:getMark(fk.MarkArmorNullified) > 0 then
        room:removePlayerMark(p, fk.MarkArmorNullified, num)
      end
    end
    data.extra_data.joysp__paoxiao = nil
  end,
}
joysp__paoxiao:addRelatedSkill(joysp__paoxiao_trigger)
local joy__xuhe = fk.CreateTriggerSkill{
  name = "joy__xuhe",
  anim_type = "drawcard",
  frequency = Skill.Compulsory,
  events = {fk.CardEffectCancelledOut, fk.CardUsing, fk.CardResponding},
  can_trigger = function(self, event, target, player, data)
    if event == fk.CardEffectCancelledOut then
      return target == player and player:hasSkill(self) and data.card.trueName == "slash"
    else
      return target == player and player:hasSkill(self) and data.card.name == "jink"
    end
  end,
  on_use = function(self, event, target, player, data)
    player:drawCards(1, self.name)
    if event == fk.CardEffectCancelledOut then
      local tar = player.room:getPlayerById(data.to)
      if not tar.dead then
        tar:drawCards(1,self.name)
      end
    end
  end,

}
joysp__zhangfei:addSkill(joysp__paoxiao)
joysp__zhangfei:addSkill(joy__xuhe)
Fk:loadTranslationTable{
  ["joysp__zhangfei"] = "张飞",
  
  ["joysp__paoxiao"] = "咆哮",
  ["#joysp__paoxiao_trigger"] = "咆哮",
  [":joysp__paoxiao"] = "锁定技，你使用【杀】无次数距离限制，每回合第二张【杀】起伤害+1；第三张【杀】起无视防具且不可响应。",
  ["joy__xuhe"] = "虚吓",
  [":joy__xuhe"] = "锁定技，你的【杀】被【闪】抵消后，你与目标各摸一张牌；你使用或打出【闪】后，摸一张牌。",

  ["$joysp__paoxiao1"] = " ",
  ["$joy__xuhe1"] = "",
  ["$joysp__paoxiao2"] = " ",
  ["$joy__xuhe2"] = "",
}

local sunshangxiang = General(extension, "joysp__sunshangxiang", "shu", 3, 3, General.Female)
local joy__liangzhu = fk.CreateTriggerSkill{
  name = "joy__liangzhu",
  anim_type = "support",
  events = {fk.HpRecover},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target.phase == Player.Play
  end,
  on_cost = function(self, event, target, player, data)
    local all_choices = {"Cancel", "draw1", "joy__liangzhu_draw2::"..target.id, "joy__liangzhu_prey::"..target.id}
    local choices = table.simpleClone(all_choices)
    if target:getEquipment(Card.SubtypeWeapon) == nil then
      table.removeOne(choices, choices[4])
    end
    local choice = player.room:askForChoice(player, choices, self.name, "#joy__liangzhu-choice::"..target.id, false, all_choices)
    if choice ~= "Cancel" then
      self.cost_data = choice
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if self.cost_data == "draw1" then
      player:drawCards(1, self.name)
    elseif self.cost_data[15] == "d" then
      room:doIndicate(player.id, {target.id})
      target:drawCards(2, self.name)
    else
      room:doIndicate(player.id, {target.id})
      room:obtainCard(player, target:getEquipment(Card.SubtypeWeapon), true, fk.ReasonPrey)
    end
  end,
}
local joy__fanxiang = fk.CreateTriggerSkill{
  name = "joy__fanxiang",
  frequency = Skill.Wake,
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and
      player.phase == Player.Start and
      player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  can_wake = function(self, event, target, player, data)
    return player:usedSkillTimes("joy__liangzhu", Player.HistoryGame) > 0
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:changeMaxHp(player, 1)
    if player:isWounded() then
      room:recover({
        who = player,
        num = 1,
        recoverBy = player,
        skillName = self.name
      })
    end
    room:handleAddLoseSkills(player, "xiaoji|joy__wujian", nil)
  end,
}
local joy__wujian = fk.CreateViewAsSkill{
  name = "joy__wujian",
  anim_type = "offensive",
  pattern = "slash",
  prompt = "#joy__wujian",
  card_filter = function(self, to_select, selected)
    return #selected == 0 and Fk:currentRoom():getCardArea(to_select) == Player.Equip and
      Self:getMark("joy__wujian_"..Fk:getCardById(to_select):getSubtypeString().."-phase") == 0
  end,
  view_as = function(self, cards)
    if #cards ~= 1 then return end
    local card = Fk:cloneCard("slash")
    card.skillName = self.name
    card:addSubcard(cards[1])
    return card
  end,
  before_use = function (self, player, use)
    player.room:setPlayerMark(player, "joy__wujian_"..Fk:getCardById(use.card.subcards[1]):getSubtypeString().."-phase", 1)
    use.extraUse = true
  end,
  enabled_at_response = function(self, player, response)
    return not response and player.phase == Player.Play
  end,
}
local joy__wujian_targetmod = fk.CreateTargetModSkill{
  name = "#joy__wujian_targetmod",
  bypass_times = function(self, player, skill, scope, card)
    return card and table.contains(card.skillNames, "joy__wujian")
  end,
}
joy__wujian:addRelatedSkill(joy__wujian_targetmod)
sunshangxiang:addSkill(joy__liangzhu)
sunshangxiang:addSkill(joy__fanxiang)
sunshangxiang:addRelatedSkill("xiaoji")
sunshangxiang:addRelatedSkill(joy__wujian)
Fk:loadTranslationTable{
  ["joysp__sunshangxiang"] = "孙尚香",
  ["joy__liangzhu"] = "良助",
  [":joy__liangzhu"] = "当一名角色于其出牌阶段内回复体力后，你可以选择一项：1.摸一张牌；2.令其摸两张牌；3.获得其装备区内的武器牌。",
  ["joy__fanxiang"] = "返乡",
  [":joy__fanxiang"] = "觉醒技，准备阶段，若你发动过〖良助〗，你加1点体力上限并回复1点体力，然后获得〖枭姬〗和〖舞剑〗。",
  ["joy__wujian"] = "舞剑",
  [":joy__wujian"] = "出牌阶段，你可以将装备区内的装备当不计次数的【杀】使用，每种类别每阶段限一次。",
  ["#joy__liangzhu-choice"] = "良助：你可以对 %dest 发动“良助”，选择执行一项",
  ["joy__liangzhu_draw2"] = "令 %dest 摸两张牌",
  ["joy__liangzhu_prey"] = "获得 %dest 的武器",
  ["#joy__wujian"] = "舞剑：你可以将装备区内的装备当不计次数的【杀】使用",
}


local caiwenji = General(extension, "joysp__caiwenji", "wei", 3, 3, General.Female)
local chenqing = fk.CreateTriggerSkill{
  name = "joy__chenqing",
  anim_type = "support",
  events = {fk.EnterDying},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0 and
    not table.every(player.room.alive_players, function (p)
      return p == player or p == target
    end)
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = {}
    for _, p in ipairs(room.alive_players) do
      if p ~= target then
        table.insert(targets, p.id)
      end
    end
    if #targets == 0 then return end
    local to = room:askForChoosePlayers(player, targets, 1, 1, "#joy__chenqing-choose", self.name, true)
    if #to > 0 then
      self.cost_data = to[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(self.cost_data)
    to:drawCards(5, self.name)
    local cards = room:askForDiscard(to, 4, 4, true, self.name, false, ".", "#joy__chenqing-discard", true)
    local suits = {}
    for _, id in ipairs(cards) do
      if Fk:getCardById(id).suit ~= Card.NoSuit then
        table.insertIfNeed(suits, Fk:getCardById(id).suit)
      end
    end
    room:throwCard(cards, self.name, to, to)
    if #suits == 4 and not to.dead and not target.dead then
      room:useVirtualCard("peach", nil, to, target, self.name)
    end
  end,
}

caiwenji:addSkill(chenqing)
caiwenji:addSkill("mozhi")
Fk:loadTranslationTable{
  ["joysp__caiwenji"] = "蔡文姬",
  ["#joysp__caiwenji"] = "金璧之才",

  ["joy__chenqing"] = "陈情",
  [":joy__chenqing"] = "每回合限一次，当一名角色进入濒死状态时，你可以令另一名角色摸五张牌，然后弃置四张牌，"..
  "若其以此法弃置的四张牌的花色各不相同，则其视为对濒死状态的角色使用一张【桃】。",

  ["#joy__chenqing-choose"] = "陈情：令一名角色摸五张牌然后弃四张牌，若花色各不相同视为对濒死角色使用【桃】",
  ["#joy__chenqing-discard"] = "陈情：需弃置四张牌，若花色各不相同则视为对濒死角色使用【桃】",
}



local pangde = General(extension, "joysp__pangde", "wei", 4)
local juesi = fk.CreateActiveSkill{
  name = "joysp__juesi",
  anim_type = "offensive",
  card_num = 1,
  target_num = 1,
  can_use = function(self, player)
    return not player:isKongcheng()
  end,
  card_filter = function(self, to_select, selected)
    return #selected == 0 and Fk:getCardById(to_select).trueName == "slash" and not Self:prohibitDiscard(Fk:getCardById(to_select))
  end,
  target_filter = function(self, to_select, selected)
    local target = Fk:currentRoom():getPlayerById(to_select)
    return #selected == 0 and not target:isNude() and Self:inMyAttackRange(target)
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    room:throwCard(effect.cards, self.name, player, player)
    local card = room:askForDiscard(target, 1, 1, true, self.name, false, ".", "#joy__juesi-discard:"..player.id)
    if #card > 0 then
      card = Fk:getCardById(card[1])
      if card.trueName ~= "slash" and  player.hp  <= target.hp  and not player.dead and not target.dead then
        if player.room:askForSkillInvoke(player,self.name,".","#joy__juesi-drawCards") then
          player:drawCards(2,self.name)
        end
      elseif card.trueName == "slash"  and not player.dead and not target.dead then
        room:useVirtualCard("duel", nil, player, target, self.name)
      end
    end
  end,
}
pangde:addSkill("joy__yuma")
pangde:addSkill(juesi)
Fk:loadTranslationTable{
  ["joysp__pangde"] = "庞德",
  ["#joysp__pangde"] = "抬榇之悟",

  ["joysp__juesi"] = "决死",
  [":joysp__juesi"] = "出牌阶段，你可以弃置一张【杀】并选择攻击范围内的一名其他角色，然后令该角色弃置一张牌。"..
  "若该角色弃置的牌不为【杀】且你的体力值小于等于该角色，则你可以摸两张牌；若弃置的是杀，你视为对其使用一张【决斗】。",

  ["#joy__juesi-discard"] = "决死：你需弃置一张牌，若不为【杀】且 %src 体力值小于等于你，其可摸两张牌，若为【杀】，视为其对你使用【决斗】",
  ["#joy__juesi-drawCards"] = "决死：是否摸两张牌",

}



local jiaxu = General(extension, "joysp__jiaxu", "wei", 3)
local joy__jianshu = fk.CreateActiveSkill{
  name = "joy__jianshu",
  anim_type = "control",
  card_num = 1,
  target_num = 1,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 and not player:isKongcheng()
  end,
  card_filter = function(self, to_select, selected)
    return #selected == 0 
  end,
  target_filter = function(self, to_select, selected)
    return #selected == 0 and to_select ~= Self.id
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    room:obtainCard(target.id, Fk:getCardById(effect.cards[1]), false, fk.ReasonGive)
    local targets = {}
    for _, p in ipairs(room:getOtherPlayers(target)) do
      if not p:isKongcheng() and p ~= player then
        table.insert(targets, p.id)
      end
    end
    if #targets == 0 then return end
    local to = room:askForChoosePlayers(player, targets, 1, 1, "#ty__jianshu-choose::"..target.id, self.name, false)
    if #to == 0 then
      to = room:getPlayerById(table.random(targets))
    else
      to = room:getPlayerById(to[1])
    end
    local pindian = target:pindian({to}, self.name)
    if pindian.results[to.id].winner then
      local winner, loser
      if pindian.results[to.id].winner == target then
        winner = target
        loser = to
      else
        winner = to
        loser = target
      end
      if not winner:isNude() and not winner.dead then
        local id = table.random(winner:getCardIds{Player.Hand, Player.Equip})
        room:obtainCard(player,id, false,fk.ReasonPrey)
      end
      if not loser.dead then
        room:loseHp(loser, 1, self.name)
      end
    else
      if not target.dead then
        room:loseHp(target, 1, self.name)
      end
      if not to.dead then
        room:loseHp(to, 1, self.name)
      end
    end
  end
}
local joy__jianshu_record = fk.CreateTriggerSkill{
  name = "#joy__jianshu_record",

  refresh_events = {fk.Deathed},
  can_refresh = function(self, event, target, player, data)
    if player:usedSkillTimes("joy__jianshu", Player.HistoryPhase) > 0 then
      local e = player.room.logic:getCurrentEvent():findParent(GameEvent.LoseHp)
      if e then
        return e.data[3] == "joy__jianshu"
      end
    end
  end,
  on_refresh = function(self, event, target, player, data)
    player:setSkillUseHistory("joy__jianshu", 0, Player.HistoryPhase)
  end,
}
local joy__yongdi = fk.CreateActiveSkill{
  name = "joy__yongdi",
  anim_type = "support",
  card_num = 0,
  target_num = 1,
  frequency = Skill.Limited,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
    return #selected == 0 
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    if table.every(room.alive_players, function(p) return p.hp >= target.hp end) and target:isWounded() then
      room:recover({
        who = target,
        num = 1,
        recoverBy = player,
        skillName = self.name
      })
    end
    if table.every(room.alive_players, function(p) return p.maxHp >= target.maxHp end) then
      room:changeMaxHp(target, 1)
    end
    if table.every(room.alive_players, function(p) return p:getHandcardNum() >= target:getHandcardNum() end) then
      target:drawCards(math.min(target.maxHp, 5), self.name)
    end
   end
}
joy__jianshu:addRelatedSkill(joy__jianshu_record)
jiaxu:addSkill("zhenlue")
jiaxu:addSkill(joy__jianshu)
jiaxu:addSkill(joy__yongdi)
Fk:loadTranslationTable{
  ["joysp__jiaxu"] = "贾诩",
  ["#joysp__jiaxu"] = "料事如神",

  ["joy__jianshu"] = "间书",
  [":joy__jianshu"] = "出牌阶段限一次，你可以将一张手牌交给一名其他角色，然后选择另一名其他角色，令这两名角色拼点：赢的角色随机交给你一张牌，"..
  "没赢的角色失去1点体力。若有角色因此死亡，此技能视为未发动过。",
  ["joy__yongdi"] = "拥嫡",
  [":joy__yongdi"] = "限定技，出牌阶段，你可选择一名角色：若其体力值全场最少，其回复1点体力；体力上限全场最少，其加1点体力上限；"..
  "手牌数全场最少，其摸体力上限张牌（最多摸五张）。",

}

local jiangwei = General(extension, "joysp__jiangwei", "wei", 4)
local kunfen = fk.CreateTriggerSkill{
  name = "joysp__kunfen",
  anim_type = "drawcard",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Finish
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:loseHp(player, 1, self.name)
    if not player.dead then player:drawCards(2, self.name) end
    if not player:prohibitUse(Fk:cloneCard("fire_attack")) then
      local Fire = Fk:cloneCard "fire_attack"
      local targets = {}
      for _, p in ipairs(player.room:getAlivePlayers()) do
        if not p:isKongcheng() then
          table.insert(targets,p.id)
        end
      end
      if #targets == 0 then return end
      local tos = room:askForChoosePlayers(player, targets, 1,1, "#joy__kunfen-choose", self.name, true)
      if #tos > 0 then
        local Fire_attack = Fk:cloneCard "fire_attack"
        Fire_attack.skillName = self.name
        room:useCard {
          from = target.id,
          tos = table.map(tos, function(pid) return { pid } end),
          card = Fire_attack,
          extraUse = true,
        }
      end
    end
  end,
}
local fengliang = fk.CreateTriggerSkill{
  name = "joysp__fengliang",
  anim_type = "defensive",
  events = {fk.EnterDying},
  frequency = Skill.Wake,
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and
      player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  can_wake = function(self, event, target, player, data)
    return player.dying
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:changeMaxHp(player, -1)
    if not player.dead then
      room:recover({
        who = player,
        num = 3 - player.hp,
        recoverBy = player,
        skillName = self.name
      })
      room:handleAddLoseSkills(player, "joy__tiaoxin", nil)
    end
  end,
}
jiangwei:addSkill(kunfen)
jiangwei:addSkill(fengliang)
jiangwei:addRelatedSkill("joy__tiaoxin")
Fk:loadTranslationTable{
  ["joysp__jiangwei"] = "姜维",
  ["joysp__kunfen"] = "困奋",
  [":joysp__kunfen"] = "结束阶段，你可失去1点体力，然后摸两张牌,并可视为对一名角色使用【火攻】。",
  ["joysp__fengliang"] = "逢亮",
  [":joysp__fengliang"] = "觉醒技，当你进入濒死状态时，你减1点体力上限并将体力值回复至3点，获得〖挑衅〗。",

  ["#joy__kunfen-choose"] = "困奋：你可以选择一名角色视为对其使用火攻。"
}

local caoren = General(extension, "joysp__caoren", "wei", 4)
local weikui = fk.CreateActiveSkill{
  name = "joysp__weikui",
  anim_type = "offensive",
  card_num = 0,
  card_filter = Util.FalseFunc,
  target_num = 1,
  target_filter = function(self, to_select, selected)
    return #selected == 0 and to_select ~= Self.id and not Fk:currentRoom():getPlayerById(to_select):isKongcheng()
  end,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 and player.hp > 0
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    room:loseHp(player, 1, self.name)
    if player.dead or target:isKongcheng() then return end
    if not table.find(target:getCardIds("h"), function(id) return Fk:getCardById(id).trueName == "jink" end) then
      U.viewCards(player, target:getCardIds("h"), self.name)
      local mark = player:getTableMark( "joysp__weikui-turn")
      table.insert(mark, target.id)
      room:setPlayerMark(player, "joysp__weikui-turn", mark)
      room:useVirtualCard("slash", nil, player, target, self.name, true)
    else
      local id = room:askForCardChosen(player, target, { card_data = { { "$Hand", target:getCardIds("h") } } }, self.name,
      "#joysp__weikui-get:"..target.id)
      room:obtainCard(player,id,false,fk.ReasonPrey)
      if player:isWounded() then
        player.room:recover({
          who = player,
          num = 1,
          recoverBy = player,
          skillName = self.name
          })
      end
    end
  end,
}
local weikui_distance = fk.CreateDistanceSkill{
  name = "#joysp__weikui_distance",
  correct_func = function() return 0 end,
  fixed_func = function(self, from, to)
    local mark = from:getTableMark( "joysp__weikui-turn")
    if table.contains(mark, to.id) then
      return 1
    end
  end,
}
weikui:addRelatedSkill(weikui_distance)
caoren:addSkill(weikui)
local lizhan = fk.CreateTriggerSkill{
  name = "joysp__lizhan",
  anim_type = "support",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Finish
    and table.find(player.room.alive_players, function(p) return p:isWounded() end)
  end,
  on_cost = function (self, event, target, player, data)
    local targets = table.filter(player.room.alive_players, function (p) return p:isWounded() end)
    local tos = player.room:askForChoosePlayers(player, table.map(targets, Util.IdMapper), 1, #targets, "#lizhan-choose", self.name, true)
    if #tos > 0 then
      self.cost_data = tos
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local tos = self.cost_data
    room:sortPlayersByAction(tos)
    for _, pid in ipairs(tos) do
      local p = room:getPlayerById(pid)
      if not p.dead then
        p:drawCards(1, self.name)
      end
    end
    for _, pid in ipairs(tos) do
      local p = room:getPlayerById(pid)
      if p:getHandcardNum() == p.hp and not player.dead then
        player:drawCards(1,self.name)
      end
    end
  end,
}
caoren:addSkill(lizhan)
Fk:loadTranslationTable{
  ["joysp__caoren"] = "曹仁",
  ["#joysp__caoren"] = "鬼神之勇",
  ["joysp__weikui"] = "伪溃",
  [":joysp__weikui"] = "出牌阶段限一次，你可以失去1点体力并选择一名有手牌的其他角色观看其手牌：若其手牌中没有【闪】，则视为你对其使用一张不计入次数限制的【杀】，且本回合你计算与其的距离视为1；若其手牌中有【闪】，你获得其中一张牌并回复一点体力。",
  ["joysp__lizhan"] = "励战",
  [":joysp__lizhan"] = "结束阶段，你可以令任意名已受伤的角色摸一张牌;然后其中每存在一名手牌数与体力值相等的角色，你摸一张牌。",
  ["#joysp__weikui-get"] = "伪溃：选择并获得 %src 一张牌",

}

local guanyu = General(extension, "joysp__guanyu", "wei", 4)
local wusheng = fk.CreateViewAsSkill{
  name = "joysp__wusheng",
  anim_type = "offensive",
  pattern = "slash",
  card_filter = function(self, to_select, selected)
    return #selected == 0 and Fk:getCardById(to_select).color == Card.Red
  end,
  view_as = function(self, cards)
    if #cards ~= 1 then return nil end
    local c = Fk:cloneCard("slash")
    c.skillName = self.name
    c:addSubcard(cards[1])
    return c
  end,
}
local wusheng_trigger = fk.CreateTriggerSkill{
  name = "#joysp__wusheng_trigger",
  main_skill = wusheng,
  mute = true,
  events = {fk.TurnStart, fk.AfterCardUseDeclared},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) then
      return (event == fk.TurnStart) or (data.card.trueName == "slash" and data.card.color == Card.Red and not data.card:isVirtual())
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.TurnStart then
      room:notifySkillInvoked(player, "joysp__wusheng", "drawcard")
      local ids = room:getCardsFromPileByRule(".|.|heart,diamond", 1, "allPiles")
      if #ids > 0 then
        room:obtainCard(player, ids[1], false, fk.ReasonPrey)
      end
    else
      room:notifySkillInvoked(player, "joysp__wusheng", "offensive")
      data.additionalDamage = (data.additionalDamage or 0) + 1
    end
  end,
}
local wusheng_targetmod = fk.CreateTargetModSkill{
  name = "#joysp__wusheng_targetmod",
  anim_type = "offensive",
  bypass_distances = function (self, player, skill, card, to)
    return player:hasSkill("joysp__wusheng") and skill.trueName == "slash_skill" and card.suit == Card.Diamond
  end
}
local danji = fk.CreateTriggerSkill{
  name = "joy__danji",
  frequency = Skill.Wake,
  events = {fk.DamageCaused,fk.CardUsing, fk.CardResponding},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) and player:usedSkillTimes(self.name, Player.HistoryGame) == 0 then
      return true
    end
  end,
  can_wake = function(self, event, target, player, data)
    if event == fk.DamageCaused then
      return player:getMark("@joy__danjidamage") + data.damage > 6
    else
      return player:getMark("@joy__danjicard") + 1 > 5
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
      room:setPlayerMark(player,"@joy__danjicard",0)
      room:setPlayerMark(player,"@joy__danjidamage",0)
      if player:isWounded() then
        player.room:recover({
          who = player,
          num = player.maxHp - player.hp,
          recoverBy = player,
          skillName = self.name
          })
      end
      room:handleAddLoseSkills(player, "joy__yuma|joy__nuzhan", nil)
  end,
}
local danji_trigger = fk.CreateTriggerSkill{
  name = "#joy__danji_trigger",
  mute = true,
  events = {fk.DamageCaused,fk.CardUsing, fk.CardResponding},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) and player:usedSkillTimes("joy__danji", Player.HistoryGame) == 0 then
      return true
    end
  end,
  on_cost =Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
      if event == fk.CardResponding or event == fk.CardUsing then
          room:addPlayerMark(player,"@joy__danjicard",1)
      elseif event == fk.DamageCaused then
        room:addPlayerMark(player,"@joy__danjidamage",data.damage)
      end
      player:setSkillUseHistory("joy__danji", 0, Player.HistoryGame)
  end,
}
local nuzhan = fk.CreateTriggerSkill{
  name = "joy__nuzhan",
  anim_type = "offensive",
  frequency = Skill.Compulsory,
  events = {fk.PreCardUse},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self.name, false, true) and data.card and data.card.trueName == "slash" and
      data.card:isVirtual() and #data.card.subcards == 1 then
        return Fk:getCardById(data.card.subcards[1]).type == Card.TypeTrick or Fk:getCardById(data.card.subcards[1]).type ~= Card.TypeTrick
    end
  end,
  on_use = function(self, event, target, player, data)
    if Fk:getCardById(data.card.subcards[1]).type ~= Card.TypeTrick then
      player.room:addPlayerMark(player,"joy__nuzhan-turn",1)
    else
      data.additionalDamage = (data.additionalDamage or 0) + 1
    end
  end,
}
local nuzhan_targetmod = fk.CreateTargetModSkill{
  name = "#joy__nuzhan_targetmod",
  residue_func = function(self, player, skill, scope)
    if skill.trueName == "slash_skill" and scope == Player.HistoryPhase then
      return player:getMark("joy__nuzhan-turn")
    end
  end,
}
wusheng:addRelatedSkill(wusheng_trigger)
wusheng:addRelatedSkill(wusheng_targetmod)
danji:addRelatedSkill(danji_trigger)
nuzhan:addRelatedSkill(nuzhan_targetmod)
guanyu:addSkill(wusheng)
guanyu:addSkill(danji)
guanyu:addRelatedSkill(nuzhan)
Fk:loadTranslationTable{
  ["joysp__guanyu"] = "关羽",
  ["#joysp__guanyu"] = "汉寿亭侯",
  ["joy__danji"] = "单骑",
  [":joy__danji"] = "觉醒技，当你累计使用和打出5张牌或累计造成6点伤害后，回满体力，然后获得技能〖驭马〗和〖怒斩〗。",
  ["joy__nuzhan"] = "怒斩",
  [":joy__nuzhan"] = "锁定技，你将非锦囊牌当【杀】使用时，本回合使用【杀】次数+1；你将锦囊牌当【杀】使用时，此【杀】伤害+1。",
  ["joysp__wusheng"] = "武圣",
  [":joysp__wusheng"] = "回合开始时，你获得一张红色牌；你可以将一张红色牌当做【杀】使用或打出；你的非转化的红色【杀】伤害+1；你使用方块【杀】无距离限制。",
  ["#joysp__wusheng_trigger"] = "武圣",
  ["#joysp__wusheng_targetmod"] = "武圣",

  ["@joy__danjicard"] = "出牌",
  ["@joy__danjidamage"] = "伤害",
}


local sp__daqiao = General(extension, "joysp__daqiao", "wu", 3, 3, General.Female)
local joy__yanxiao = fk.CreateActiveSkill{
  name = "joy__yanxiao",
  anim_type = "support",
  card_num = 1,
  target_num = 1,
  prompt = "#joy__yanxiao",
  can_use = function(self, player)
    return not player:isNude()
  end,
  card_filter = function(self, to_select, selected)
    return #selected == 0 and Fk:getCardById(to_select).suit == Card.Diamond
  end,
  target_filter = function(self, to_select, selected)
    return #selected == 0 and not Fk:currentRoom():getPlayerById(to_select):hasDelayedTrick("yanxiao_trick")
  end,
  on_use = function(self, room, effect)
    local target = room:getPlayerById(effect.tos[1])
    local card = Fk:cloneCard("yanxiao_trick")
    card:addSubcards(effect.cards)
    target:addVirtualEquip(card)
    room:moveCardTo(card, Card.PlayerJudge, target, fk.ReasonJustMove, self.name)
  end,
}
local joy__yanxiao_trigger = fk.CreateTriggerSkill{
  name = "#joy__yanxiao_trigger",
  mute = true,
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player.phase == Player.Judge and player:hasDelayedTrick("yanxiao_trick")
  end,
  on_cost = function(self, event, target, player, data)
    return true
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke("joy__yanxiao")
    room:notifySkillInvoked(player, "joy__yanxiao")
    local dummy = Fk:cloneCard("dilu")
    dummy:addSubcards(player:getCardIds("j"))
    room:obtainCard(player.id, dummy, true, fk.ReasonJustMove)
    local judge = {
      who = player,
      reason = "joy__yanxiao",
    }
    room:judge(judge)
    if judge.card.color == Card.Red then
      player:drawCards(1, "joy__yanxiao")
    elseif judge.card.color == Card.Black then
      room:setPlayerMark(player, "joy__yanxiao-turn", 1)
    end
  end,
}
local joy__yanxiao_targetmod = fk.CreateTargetModSkill{
  name = "#joy__yanxiao_targetmod",
  residue_func = function(self, player, skill, scope)
    if skill.trueName == "slash_skill" and player:getMark("joy__yanxiao-turn") > 0 and scope == Player.HistoryPhase then
      return 1
    end
    return 0
  end,
}
local joy__guose = fk.CreateTriggerSkill{
  name = "joy__guose",
  frequency = Skill.Compulsory,
  anim_type = "drawcard",
  events = {fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self.name) then
      for _, move in ipairs(data) do
        if move.from == player.id and move.extra_data and move.extra_data.joy__guose then
          return true
        end
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local n = 0
    for _, move in ipairs(data) do
      if move.from == player.id and move.extra_data and move.extra_data.joy__guose then
        n = n + move.extra_data.joy__guose
      end
    end
    player:drawCards(n, self.name)
  end,

  refresh_events = {fk.BeforeCardsMove},
  can_refresh = function(self, event, target, player, data)
    if player:hasSkill(self.name) then
      for _, move in ipairs(data) do
        if move.from == player.id then
          for _, info in ipairs(move.moveInfo) do
            if (info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip) and Fk:getCardById(info.cardId).suit == Card.Diamond then
              return true
            end
          end
        end
      end
    end
  end,
  on_refresh = function(self, event, target, player, data)
    for _, move in ipairs(data) do
      if move.from == player.id then
        local n = 0
        for _, info in ipairs(move.moveInfo) do
          if (info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip) and Fk:getCardById(info.cardId).suit == Card.Diamond then
            n = n + 1
          end
        end
        if n > 0 then
          move.extra_data = move.extra_data or {}
          move.extra_data.joy__guose = n
        end
      end
    end
  end,
}
local joy__anxian = fk.CreateTriggerSkill{
  name = "joy__anxian",
  mute = true,
  events = {fk.TargetSpecifying, fk.TargetConfirming},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self.name) and data.card and data.card.trueName == "slash" then
      if event == fk.TargetSpecifying then
        return not table.contains(data.card.skillNames, self.name)
      else
        return not player:isNude()
      end
    end
  end,
  on_trigger = function(self, event, target, player, data)
    if event == fk.TargetSpecifying then
      for _, id in ipairs(AimGroup:getAllTargets(data.tos)) do
        local p = player.room:getPlayerById(id)
        if not player.dead and player:hasSkill(self.name) and not p.dead and not p:isKongcheng() then
          self:doCost(event, target, player, id)
        end
      end
    else
      self:doCost(event, target, player, data)
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if event == fk.TargetSpecifying then
      return room:askForSkillInvoke(player, self.name, nil, "#joy__anxian1-invoke::"..data)
    else
      local card = room:askForDiscard(player, 1, 1, true, self.name, true, ".",
        "#joy__anxian2-invoke::"..data.from..":"..data.card:toLogString(), true)
      if #card > 0 then
        self.cost_data = card
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.TargetSpecifying then
      player:broadcastSkillInvoke(self.name, 1)
      room:notifySkillInvoked(player, self.name, "control")
      local p = room:getPlayerById(data)
      if not p:isKongcheng() then
        room:askForDiscard(p, 1, 1, false, self.name, false)
      end
    else
      player:broadcastSkillInvoke(self.name, 2)
      room:notifySkillInvoked(player, self.name, "defensive")
      table.insertIfNeed(data.nullifiedTargets, player.id)
      local suit = Fk:getCardById(self.cost_data[1]).suit
      room:throwCard(self.cost_data, self.name, player, player)
      local from = room:getPlayerById(data.from)
      if not from.dead then
        from:drawCards(1, self.name)
      end
      if not player.dead and not from.dead and suit == Card.Diamond then
        room:useVirtualCard("slash", nil, player, from, self.name, true)
      end
    end
  end
}
joy__yanxiao:addRelatedSkill(joy__yanxiao_trigger)
joy__yanxiao:addRelatedSkill(joy__yanxiao_targetmod)
sp__daqiao:addSkill(joy__yanxiao)
sp__daqiao:addSkill(joy__guose)
sp__daqiao:addSkill(joy__anxian)
Fk:loadTranslationTable{
  ["joysp__daqiao"] = "大乔",
  ["joy__yanxiao"] = "言笑",
  [":joy__yanxiao"] = "出牌阶段，你可以将一张<font color='red'>♦</font>牌置于一名角色的判定区内，判定区有“言笑”牌的角色下个判定阶段开始时，"..
  "获得其判定区内所有牌并进行一次判定，若结果为：红色，其摸一张牌；黑色，本回合出牌阶段使用【杀】次数上限+1。",
  ["joy__guose"] = "国色",
  [":joy__guose"] = "锁定技，当你失去一张<font color='red'>♦</font>牌后，你摸一张牌。",
  ["joy__anxian"] = "安娴",
  [":joy__anxian"] = "当你不以此法使用【杀】指定目标时，你可以令目标弃置一张手牌；当你成为【杀】的目标时，你可以弃置一张牌令之无效，然后使用者"..
  "摸一张牌，若你弃置的是<font color='red'>♦</font>牌，你视为对其使用一张【杀】。",
  ["#joy__yanxiao"] = "言笑：你可以将一张<font color='red'>♦</font>牌置于一名角色的判定区内，其判定阶段开始时获得判定区内所有牌",
  ["#joy__anxian1-invoke"] = "安娴：你可以令 %dest 弃置一张手牌",
  ["#joy__anxian2-invoke"] = "安娴：你可以弃置一张牌令 %dest 对你使用的%arg无效，若弃置的是<font color='red'>♦</font>，你视为对其使用【杀】",
}

local sp__xiaoqiao = General(extension, "joysp__xiaoqiao", "wu", 3, 3, General.Female)
local joy__xingwu = fk.CreateActiveSkill{
  name = "joy__xingwu",
  anim_type = "offensive",
  card_num = 1,
  target_num = 1,
  prompt = "#joy__xingwu",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 and not player:isKongcheng()
  end,
  card_filter = function(self, to_select, selected)
    return #selected == 0 and Fk:currentRoom():getCardArea(to_select) == Player.Hand and not Self:prohibitDiscard(Fk:getCardById(to_select))
  end,
  target_filter = function(self, to_select, selected)
    return #selected == 0 and to_select ~= Self.id
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    room:throwCard(effect.cards, self.name, player, player)
    if player.dead then return end
    player:turnOver()
    if player.dead then return end
    if #target:getCardIds("e") > 0 then
      local id = room:askForCardChosen(player, target, "e", self.name)
      room:throwCard({id}, self.name, target, player)
    end
    if target.dead then return end
    local n = target.gender == General.Male and 2 or 1
    room:damage{
      from = player,
      to = target,
      damage = n,
      skillName = self.name,
    }
  end,
}
local joy__luoyan = fk.CreateTriggerSkill{
  name = "joy__luoyan",
  anim_type = "special",
  frequency = Skill.Compulsory,
  events = {fk.AfterSkillEffect},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self.name) and data.name == "joy__xingwu"
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local skills = {}
    for _, s in ipairs({"joyex__tianxiang", "joyex__hongyan"}) do
      if not player:hasSkill(s, true) then
        table.insert(skills, s)
      end
    end
    if #skills == 0 then return end
    room:setPlayerMark(player, "joy__luoyan", skills)
    room:handleAddLoseSkills(player, table.concat(skills, "|"), nil, true, false)
  end,

  refresh_events = {fk.EventPhaseStart},
  can_refresh = function (self, event, target, player, data)
    return target == player and player.phase == Player.Play and player:getMark("joy__luoyan") ~= 0
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    local skills = player:getMark("joy__luoyan")
    room:setPlayerMark(player, "joy__luoyan", 0)
    room:handleAddLoseSkills(player, "-"..table.concat(skills, "|-"), nil, true, false)
  end,
}
local joy__huimou = fk.CreateTriggerSkill{
  name = "joy__huimou",
  anim_type = "support",
  events = {fk.CardUseFinished, fk.CardRespondFinished, fk.SkillEffect},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self.name) and player.phase == Player.NotActive and
      table.find(player.room.alive_players, function(p) return not p.faceup end) then
      if event == fk.SkillEffect then
        return data.name == "joyex__tianxiang"
      else
        return data.card.suit == Card.Heart
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local to = room:askForChoosePlayers(player, table.map(table.filter(room.alive_players, function(p)
      return not p.faceup end), function(p) return p.id end),
      1, 1, "#joy__huimou-choose", self.name, true)
    if #to > 0 then
      self.cost_data = to[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    player.room:getPlayerById(self.cost_data):turnOver()
  end,
}
sp__xiaoqiao:addSkill(joy__xingwu)
sp__xiaoqiao:addSkill(joy__luoyan)
sp__xiaoqiao:addSkill(joy__huimou)
Fk:loadTranslationTable{
  ["joysp__xiaoqiao"] = "小乔",
  ["joy__xingwu"] = "星舞",
  [":joy__xingwu"] = "出牌阶段限一次，你可以弃置一张手牌并翻面，弃置一名其他角色装备区内一张牌，然后对其造成1点伤害；若其为男性角色，则改为2点。",
  ["joy__luoyan"] = "落雁",
  [":joy__luoyan"] = "锁定技，当你发动〖星舞〗后，直到你下个出牌阶段开始时，你获得〖天香〗和〖红颜〗。",
  ["joy__huimou"] = "回眸",
  [":joy__huimou"] = "当你于回合外使用或打出<font color='red'>♥</font>牌后，或当你发动〖天香〗时，你可以令一名武将牌背面朝上的角色翻至正面。",
  ["#joy__xingwu"] = "星舞：弃置一张手牌并翻面，弃置一名其他角色装备区内一张牌，对其造成伤害",
  ["#joy__huimou-choose"] = "回眸：你可以令一名武将牌背面朝上的角色翻至正面",
}


local pangtong = General(extension, "joysp__pangtong", "wu", 3)
local guolun = fk.CreateActiveSkill{
  name = "joy__guolun",
  anim_type = "control",
  card_num = 0,
  target_num = 1,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected, selected_cards)
    return #selected == 0 and to_select ~= Self.id and not Fk:currentRoom():getPlayerById(to_select):isKongcheng()
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    local id1 = room:askForCardChosen(player, target, "h", self.name)
    target:showCards(id1)
    if not target.dead and not player:isNude() then
      local n1 = Fk:getCardById(id1).number
      local card = room:askForCard(player, 1, 1, false, self.name, true, ".", "#joy__guolun-card:::"..tostring(n1))
      if #card > 0 then
        local id2 = card[1]
        player:showCards(id2)
        local n2 = Fk:getCardById(id2).number
        if player.dead then return end
        local move1 = {
          from = effect.from,
          ids = {id2},
          to = effect.tos[1],
          toArea = Card.PlayerHand,
          moveReason = fk.ReasonJustMove,
          proposer = effect.from,
          skillName = self.name,
        }
        local move2 = {
          from = effect.tos[1],
          ids ={id1},
          to = effect.from,
          toArea = Card.PlayerHand,
          moveReason = fk.ReasonJustMove,
          proposer = effect.from,
          skillName = self.name,
        }
        room:moveCards(move1, move2)
        if n2 > n1 and not target.dead then
          target:drawCards(1, self.name)
          room:recover({
            who = player,
            num = 1,
            recoverBy = player,
            skillName = self.name,
          })
        elseif n1 > n2 and not player.dead then
          player:drawCards(2, self.name)
        end
      end
    end
  end,
}
local songsang = fk.CreateTriggerSkill{
  name = "joy__songsang",
  anim_type = "support",
  events = {fk.Death},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) 
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:changeMaxHp(player, 1)
    room:recover({
      who = player,
      num = 1,
      recoverBy = player,
      skillName = self.name,
    })
  end,
}
pangtong:addSkill(guolun)
pangtong:addSkill(songsang)
pangtong:addSkill("zhanji")
Fk:loadTranslationTable{
  ["joysp__pangtong"] = "庞统",
  ["#joysp__pangtong"] = "南州士冠",

  ["joy__guolun"] = "过论",
  [":joy__guolun"] = "出牌阶段限一次，你可以展示一名其他角色的一张手牌，然后你可以展示一张手牌，交换这两张牌"..
    "若其选择的点数小，其摸一张牌，你回复一点体力；"..
    "若你选择的点数小，你摸两张牌",
  ["joy__songsang"] = "送丧",
  [":joy__songsang"] = "当其他角色死亡时，你可加1点体力上限并回复1点体力。",

  ["#joy__guolun-card"] = "过论：你可以选择一张牌并交换双方的牌（对方点数为%arg）",

}


local menghuo = General(extension, "joysp__menghuo", "qun", 4)
local function doManwang(player, i)
  local room = player.room
  if i == 1 then
    room:handleAddLoseSkills(player, "panqin", nil, true, false)
  elseif i == 2 then
    player:drawCards(1, "manwang")
  elseif i == 3 then
    if player:isWounded() then
      room:recover{
        who = player,
        num = 1,
        recoverBy = player,
        skillName = "manwang",
      }
    end
  elseif i == 4 then
    player:drawCards(2, "manwang")
    room:handleAddLoseSkills(player, "-panqin", nil, true, false)
  end
end
local manwang = fk.CreateActiveSkill{
  name = "joy__manwang",
  anim_type = "special",
  min_card_num = 1,
  target_num = 0,
  can_use = function(self, player)
    return not player:isNude() and player:usedSkillTimes(self.name, Player.HistoryPhase) <= 21
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    room:throwCard(effect.cards, self.name, player, player)
    for i = 1, #effect.cards, 1 do
      if i > 4 or player:getMark("@manwang") > (4-i) then return end
      doManwang(player, i)
    end
    if not player:hasSkill("joy__huoshou") then
      room:setPlayerMark(player,"joy__manwang",1)
      room:handleAddLoseSkills(player, "joy__huoshou", nil, true, false)
    end
  end,

}
local manwang_refresh = fk.CreateTriggerSkill{
  name = "#joy__manwang_refresh",
  mute = true,
  anim_type = "offensive",
  refresh_events = {fk.TurnStart},
  can_refresh = function(self, event, target, player, data)
    return target == player and player:getMark("joy__manwang") > 0 and event == fk.TurnStart
  end,
  on_refresh = function(self, event, target, player, data)
    player.room:handleAddLoseSkills(player, "-joy__huoshou", nil, true, false)
    player.room:setPlayerMark(player, "joy__manwang", 0)
  end,
}
manwang:addRelatedSkill(manwang_refresh)
menghuo:addSkill(manwang)
menghuo:addRelatedSkill("panqin")
menghuo:addRelatedSkill("joy__huoshou")
Fk:loadTranslationTable{
  ["joysp__menghuo"] = "孟获",
  ["#joysp__menghuo"] = "夷汉并服",

  ["joy__manwang"] = "蛮王",
  [":joy__manwang"] = "出牌阶段，你可以弃置任意张牌依次执行前等量项：1.获得〖叛侵〗；2.摸一张牌；3.回复1点体力；4.摸两张牌并失去〖叛侵〗;若如此做，至到你的下回合开始前，你拥有技能〖祸首〗。"..
  '<br /><font color="grey">（为防止某些情况永动，弃牌技每阶段限20次）</font>',
  
}

local taishici = General(extension, "joysp__taishici", "qun", 4)
local jixu = fk.CreateActiveSkill{
  name = "joy__jixu",
  anim_type = "control",
  card_num = 0,
  min_target_num = 1,
  max_target_num = 4,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
      return to_select ~= Self.id
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    room:sortPlayersByAction(effect.tos)
    local targets = table.map(effect.tos, function(id) return room:getPlayerById(id) end)
    for _, p in ipairs(targets) do
      local choices = {"yes", "no"}
      p.request_data = json.encode({choices, choices, self.name, "#jixu-choice:"..player.id})
    end
    room:notifyMoveFocus(room.alive_players, self.name)
    room:doBroadcastRequest("AskForChoice", targets)

    for _, p in ipairs(targets) do
      local choice
      if p.reply_ready then
        choice = p.client_reply
      else
        p.client_reply = "yes"
        choice = "yes"
      end
      room:sendLog{
        type = "#jixu-quest",
        from = p.id,
        arg = choice,
      }
    end
    local right = table.find(player.player_cards[Player.Hand], function(id)
      return Fk:getCardById(id).trueName == "slash" end) and "yes" or "no"
    local n = 1
    local wrong = {}
    for _, p in ipairs(targets) do
      local choice = p.client_reply
      if choice ~= right then
        room:doIndicate(player.id, {p.id})
        if not p:isNude() then
          local id = room:askForCardChosen(player, p, "he", self.name)
          room:throwCard({id}, self.name, p, player)
        end
        if not p.dead then
          room:useVirtualCard("slash", nil, player, p, self.name, true)
        end
      else 
        n = n + 1
      end
    end
    if n > 0 and not player.dead then
      player:drawCards(n, self.name)
      room:addPlayerMark(player,"joy__jixu-turn",n)
    end
  end,
}
local jixu_maxcards = fk.CreateMaxCardsSkill{
  name = "#joy__jixu_maxcards",
  correct_func = function(self, player)
    return player:getMark("joy__jixu-turn")
  end,
}
jixu:addRelatedSkill(jixu_maxcards)
taishici:addSkill(jixu)
Fk:loadTranslationTable{
  ["joysp__taishici"] = "太史慈",
  ["#joysp__taishici"] = "北海酬恩",

  ["joy__jixu"] = "击虚",
  [":joy__jixu"] = "出牌阶段限一次，你可令至多4名其他角色同时猜测你的手牌中是否有【杀】。猜错的角色，你弃置其一张牌，然后视为对其使用一张【杀】。"..
  "然后你摸X张牌，且本回合手牌上限+X(X为猜对的角色数+1）。",

}

local huangyueying = General(extension, "joysp__huangyueying", "qun", 3, 3, General.Female)
local jiqiao = fk.CreateTriggerSkill{
  name = "joy__jiqiao",
  anim_type = "drawcard",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Play and not player:isNude()
  end,
  on_cost = function(self, event, target, player, data)
    local n = #player.room:askForDiscard(player, 1, 999, true, self.name, true, ".|.|.|.|.|^trick", "#joy__jiqiao-invoke")
    if n > 0 then
      self.cost_data = n
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local cards = room:getNCards(2*self.cost_data)
    room:moveCards{
      ids = cards,
      toArea = Card.Processing,
      moveReason = fk.ReasonJustMove,
      skillName = self.name,
    }
    local get = {}
    for i = #cards, 1, -1 do
      if Fk:getCardById(cards[i]).type == Card.TypeTrick then
        table.insert(get, cards[i])
        table.removeOne(cards, cards[i])
      end
    end
    if #get > 0 then
      room:delay(1000)
      local dummy = Fk:cloneCard("dilu")
      dummy:addSubcards(get)
      room:obtainCard(player.id, dummy, true, fk.ReasonJustMove)
    else
      local cards = room:getCardsFromPileByRule(".|.|.|.|.|trick")
      if #cards > 0 and not player.dead then
        local get = cards[1]
        room:obtainCard(player, get, false, fk.ReasonDraw)
      end
    end
    if #cards > 0 then
      room:delay(1000)
      room:moveCards{
        ids = cards,
        toArea = Card.DiscardPile,
        moveReason = fk.ReasonJustMove,
        skillName = self.name,
      }
    end
  end,
}
local linglong = fk.CreateTriggerSkill{
  name = "joy__linglong",
  events = {fk.AskForCardUse, fk.AskForCardResponse},
  frequency = Skill.Compulsory,
  anim_type = "defensive",
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and not player:isFakeSkill(self) and
      (data.cardName == "jink" or (data.pattern and Exppattern:Parse(data.pattern):matchExp("jink|0|nosuit|none"))) and
      not player:getEquipment(Card.SubtypeArmor) and player:getMark(fk.MarkArmorNullified) == 0
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, data,"#joy__linglong")
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local judgeData = {
      who = player,
      reason = "eight_diagram",
      pattern = ".|.|heart,diamond",
    }
    room:judge(judgeData)

    if judgeData.card.color == Card.Red then
      if event == fk.AskForCardUse then
        data.result = {
          from = player.id,
          card = Fk:cloneCard('jink'),
        }
        data.result.card.skillName = "eight_diagram"
        data.result.card.skillName = "joy__linglong"

        if data.eventData then
          data.result.toCard = data.eventData.toCard
          data.result.responseToEvent = data.eventData.responseToEvent
        end
      else
        data.result = Fk:cloneCard('jink')
        data.result.skillName = "eight_diagram"
        data.result.skillName = "joy__linglong"
      end
      return true
    end
  end
}
local linglong_maxcards = fk.CreateMaxCardsSkill{
  name = "#joy__linglong_maxcards",
  correct_func = function(self, player)
    if player:hasSkill("joy__linglong") and player:getEquipment(Card.SubtypeOffensiveRide) == nil and
      player:getEquipment(Card.SubtypeDefensiveRide) == nil then
      return 1
    end
    return 0
  end,
}
local linglong_targetmod = fk.CreateTargetModSkill{
  name = "#joy__linglong_targetmod",
  frequency = Skill.Compulsory,
  bypass_distances = function(self, player, skill, card)
    return player:hasSkill("joy__linglong") and #player:getCardIds("e") == 0 and card and card.type == Card.TypeTrick
  end,
}
local linglong_trigger = fk.CreateTriggerSkill{
  name = "#joy__linglong_trigger",
  anim_type = "drawcard",
  events = {fk.CardUsing},
  can_trigger = function(self, event, target, player, data)
    return target == player and #player:getCardIds("e") == 0 and player:hasSkill("joy__linglong") and data.card:isCommonTrick() and #data.card.subcards == 0
  end,
  on_use = function(self, event, target, player, data)
    player:drawCards(1, self.name)
  end,
}
local jizhi = fk.CreateTriggerSkill{
  name  = "joysp__jizhi"

}
linglong:addRelatedSkill(linglong_trigger)
linglong:addRelatedSkill(linglong_maxcards)
linglong:addRelatedSkill(linglong_targetmod)
huangyueying:addSkill(jiqiao)
huangyueying:addSkill(linglong)
huangyueying:addRelatedSkill("qicai")
huangyueying:addRelatedSkill(jizhi)
Fk:loadTranslationTable{
  ["joysp__huangyueying"] = "黄月英",
  ["#joysp__huangyueying"] = "闺中璞玉",

  ["joy__jiqiao"] = "机巧",
  [":joy__jiqiao"] = "出牌阶段开始时，你可以弃置任意张非锦囊牌，然后亮出牌堆顶两倍数量的牌，获得其中的锦囊牌，若其中没有锦囊牌，你获得一张锦囊牌。",
  ["joy__linglong"] = "玲珑",
  [":joy__linglong"] = "锁定技，若你的装备区没有防具牌，视为你装备着【八卦阵】；若你的装备区没有坐骑牌，你的手牌上限+1；"..
  "若你的装备区没有装备，视为你拥有技能〖奇才〗和〖集智〗。",
  ["#joy__jiqiao-invoke"] = "机巧：你可以弃置任意张非锦囊牌，亮出牌堆顶两倍数量的牌并获得其中的锦囊牌",
  ["joysp__jizhi"] = "集智",
  [":joysp__jizhi"] = "当你使用普通锦囊牌时，你可以摸一张牌。",
  ["#joy__linglong_trigger"] = "集智",
  ["#joy__linglong_targetmod"] = "奇才",
  ["#joy__linglong"] = "你想发动技能“八卦阵”吗？",
}

local zhanghe = General(extension, "joysp__zhanghe", "qun", 4)
local zhouxuan = fk.CreateTriggerSkill{
  name = "joysp__zhouxuan",
  anim_type = "drawcard",
  expand_pile = "joy__xuan",
  events = {fk.CardUsing,fk.CardResponding,fk.EventPhaseStart,fk.CardUseFinished},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self.name) then
      if event == fk.CardUsing or event == fk.CardResponding then
        return true
      elseif event == fk.EventPhaseStart then
        return player.phase == Player.Discard and #player:getPile("joy__xuan") < 5 and not player:isKongcheng()
      elseif event == fk.CardUseFinished then
        return player:getMark("joy__zhouxuan") > 0
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    if  #player:getPile("joy__xuan") == 0 and event == fk.CardUsing  then
      player.room:setPlayerMark(player,"joy__zhouxuan",1)
    end
      if event == fk.EventPhaseStart then
        local x = 5 - #player:getPile("joy__xuan")
        local cards = player.room:askForCard(player, 1, x, false, self.name, true,
        ".", "#joy__zhouxuan-invoke:::".. tostring(x))
        if #cards > 0 then
          self.cost_data = cards
          return true
        end
      elseif event == fk.CardUsing or event == fk.CardResponding then
        return #player:getPile("joy__xuan") > 0
      elseif event == fk.CardUseFinished then
        player.room:setPlayerMark(player,"joy__zhouxuan",0)
        if #player:getPile("joy__xuan") == 0 and not data.card:isVirtual() and player.room:getCardArea(data.card) == Card.Processing then
          return player.room:askForSkillInvoke(player,self.name,data,"#joy__zhouxuan-invoke2")
        end
      end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.CardUsing or event == fk.CardResponding then
        local n = 1
        local x = 1
        if not table.every(room:getOtherPlayers(player), function(p)
         return #p.player_cards[Player.Hand] < #player.player_cards[Player.Hand] end) and #player:getPile("joy__xuan") > 1 then
          n = #player:getPile("joy__xuan")
          x = 2
        end
        player:drawCards(n,self.name)
        local cids = room:askForCard(player, x, x, false, self.name, false, ".|.|.|joy__xuan|.|.", "#joy__zhouxuan-card:::"..x, "joy__xuan")
        if #player:getPile("joy__xuan") == 0 then return false end
        room:moveCardTo(cids, Card.DiscardPile, nil, fk.ReasonPutIntoDiscardPile, self.name, "joy__xuan")
    elseif event == fk.EventPhaseStart then
      player:addToPile("joy__xuan", self.cost_data, false, self.name)
    elseif event == fk.CardUseFinished then
      player:addToPile("joy__xuan", data.card, false, self.name)
    end
  end,
}
zhanghe:addSkill(zhouxuan)
Fk:loadTranslationTable{
  ["joysp__zhanghe"] = "张郃",
  ["#joysp__zhanghe"] = "倾柱覆州",

  ["joysp__zhouxuan"] = "周旋",
  [":joysp__zhouxuan"] = "弃牌阶段开始时，你可将任意张手牌扣置于武将牌上（均称为「旋」，至多五张）。"..
  "<br>当你使用或打出一张牌时:<br>①若你有「旋」，你摸一张牌并移去一张「旋」，"..
  "若你不是唯一手牌数最大的角色，则改为摸X张牌，然后移去两张「旋」。(X为「旋」的数量）"..
  "<br>②若你没有「旋」，你可在使用的牌结算后将其置为「旋」。",
  ["joy__xuan"] = "旋",
  ["#joy__zhouxuan-invoke"] = "你可以发动 周旋，将至多%arg张手牌置为「旋」",
  ["#joy__zhouxuan-invoke2"] = "你可以发动 周旋，将此次使用的牌置为「旋」",
  ["#joy__zhouxuan-card"] = "选择将%arg张「旋」置入弃牌堆",

  ["$joy__zhouxuan1"] = " ",
  ["$joy__zhouxuan2"] = " ",
  ["~joy__zhanghe"] = " ",
}

local machao = General(extension, "joysp__machao", "qun", 4)
local zhuiji = fk.CreateTriggerSkill{
  name = "joysp__zhuiji",
  anim_type = "offensive",
  events = {fk.CardUsing},
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and
      data.card.trueName == "slash"  and
      table.find(player.room:getOtherPlayers(player), function(p) return p.hp >= player.hp end)
  end,
  on_use = function(self, event, target, player, data)
    local targets = table.filter(player.room:getOtherPlayers(player), function(p) return p.hp >= player.hp end)
    if #targets > 0 then
      data.disresponsiveList = data.disresponsiveList or {}
      for _, p in ipairs(targets) do
        table.insertIfNeed(data.disresponsiveList, p.id)
      end
    end
  end,
}
local zhuiji_distance = fk.CreateDistanceSkill{
  name = "#joysp__zhuiji_distance",
  frequency = Skill.Compulsory,
  fixed_func = function(self, from, to)
    if from:hasSkill(zhuiji) and from.hp >= to.hp then
      return 1
    end
  end,
}
local shichou = fk.CreateTriggerSkill{
  name = "joysp__shichou",
  anim_type = "offensive",
  events = {fk.AfterCardTargetDeclared,fk.CardUseFinished},
  can_trigger = function(self, event, target, player, data)
    if  target == player and player:hasSkill(self) and data.card.trueName == "slash" then
      if event == fk.AfterCardTargetDeclared  then
        local current_targets = TargetGroup:getRealTargets(data.tos)
        for _, p in ipairs(player.room.alive_players) do
          if not table.contains(current_targets, p.id) and not player:isProhibited(p, data.card) and
              data.card.skill:modTargetFilter(p.id, current_targets, data.from, data.card, true) then
            return true
          end
        end
      elseif event == fk.CardUseFinished then
        return   player:getMark("joysp__shichou-turn") > 0 or not data.damageDealt 
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if event == fk.AfterCardTargetDeclared then
      local current_targets = TargetGroup:getRealTargets(data.tos)
      local targets = {}
      for _, p in ipairs(room.alive_players) do
        if not table.contains(current_targets, p.id) and not player:isProhibited(p, data.card) and
            data.card.skill:modTargetFilter(p.id, current_targets, data.from, data.card, true) then
          table.insert(targets, p.id)
        end
      end
      local n = player:getLostHp() + 1
      local tos = room:askForChoosePlayers(player, targets, 1, n,
      "#joysp__shichou-choose:::"..data.card:toLogString()..":"..tostring(n), self.name, true)
      if #tos > 0 then
        self.cost_data = tos
        return true
      end
    elseif event == fk.CardUseFinished then
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    if event == fk.AfterCardTargetDeclared then
      table.insertTable(data.tos, table.map(self.cost_data, function (p)
        return {p}
      end))
    elseif not data.damageDealt and not player.dead then
      local ids = player.room:getCardsFromPileByRule("slash|.|.", 1, "DrawPile")
      if #ids > 0 then
        player.room:obtainCard(player, ids[1], true, fk.ReasonPrey)
      end
    elseif player:getMark("joysp__shichou-turn") > 0 and not player.dead then
      player:drawCards(player:getMark("joysp__shichou-turn"),self.name)
      player.room:setPlayerMark(player,"joysp__shicho-turn",0)
    end
  end,
  refresh_events = {fk.Damage},
  can_refresh = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.card and data.card.trueName == "slash" and player:getMark("joysp__shichou_max-turn") < 3
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    room:addPlayerMark(player,"joysp__shichou_max-turn",1)
    room:addPlayerMark(player,"joysp__shichou-turn",1)
  end,
}
zhuiji:addRelatedSkill(zhuiji_distance)
machao:addSkill(zhuiji)
machao:addSkill(shichou)

Fk:loadTranslationTable{
  ["joysp__machao"] = "马超",
  ["#joysp__machao"] = "西凉的猛狮",
  ["joysp__zhuiji"] = "追击",
  [":joysp__zhuiji"] = "锁定技，你计算与体力值小于等于你的角色的距离视为为1。"..
  "体力值大于等于你的角色无法响应你使用的【杀】。",
  ["joysp__shichou"] = "誓仇",
  [":joysp__shichou"] = "①当你使用【杀】指定目标后，可以多选择至多X名角色为目标（X为你已损失的体力值+1）。"..
  "<br>②你使用【杀】结算后，若没有造成伤害，你从牌堆获得一张【杀】；若造成了伤害，每造成1次伤害你摸1张牌（每回合至多摸3张）。",
  ["@joysp__shichou_max-turn"] = "上限",
  ["@joysp__shichou-turn"] = "摸牌",

  ["#joysp__shichou-choose"] = "你可以为此【%arg】额外指定至多%arg2个目标",

  ["$joy__shichou1"] = " ",
  ["$joy__shichou2"] = " ",
  ["~joy__machao"] = " ",
}


local zhangliao = General(extension, "joysp__zhangliao", "qun", 4)
Fk:addPoxiMethod{
  name = "joy__mubing_prey",
  card_filter = function(to_select, selected, data)
    if table.contains(data[2][2],to_select) then return true end
    if #selected > 0  then
      local a,b = 0,0
      for _, cid in ipairs(selected) do
        if table.contains(data[1][2],cid) then
          a = a +  Fk:getCardById(cid).number
        else
          b = b +  Fk:getCardById(cid).number
        end
      end
      return Fk:getCardById(to_select).number <= (b-a)
    end
  end,
  feasible = function(selected, data)
    if not data or #selected == 0 then return false end
    local count = 0
    for _, id in ipairs(selected) do
      local num = Fk:getCardById(id).number
      if table.contains(data[1][2], id) then
        count = count - num
      else
        count = count + num
      end
    end
    return count >= 0
  end,
  prompt = function ()
    return Fk:translate("#joy__mubing-prompt")
  end
}
local mubing = fk.CreateActiveSkill{
  name = "joy__mubing",
  anim_type = "drawcard",
  prompt = "展示牌堆顶四张牌，然后你弃置任意张手牌，获得其中点数和不小于弃置牌点数和的牌",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) < 1
  end,
  card_filter = Util.FalseFunc,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local cards = room:getNCards(4)
    room:moveCards({
      ids = cards,
      toArea = Card.Processing,
      moveReason = fk.ReasonPut,
    })
    local can_throw = table.filter(player:getCardIds("h"), function(id) return not player:prohibitDiscard(Fk:getCardById(id)) end)
    if #can_throw > 0 then
      local result = room:askForPoxi(player, "joy__mubing_prey", {
        { "joy__mubing_to_prey", cards },
        { "joy__mubing_to_throw", can_throw },
      }, nil, true)
      local get, throw = {}, {}
      for _, id in ipairs(result) do
        if table.contains(cards, id) then
          table.insert(get, id)
        else
          table.insert(throw, id)
        end
      end
      if #throw > 0 then
        room:throwCard(throw, self.name, player, player)
      end
      if #get > 0 and not player.dead then
        local dummy = Fk:cloneCard("dilu")
        dummy:addSubcards(get)
        room:obtainCard(player.id, dummy, true, fk.ReasonPrey)
        for _, id in ipairs(get) do
          local card = Fk:getCardById(id)
          room:setCardMark(card,"@@joy__mubing-inhand",1)
        end
      end
    end
  end,
}
local ziqu = fk.CreateTriggerSkill{
  name = "joy__ziqu",
  anim_type = "control",
  events = {fk.DamageCaused},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) then
      return not table.contains(player:getTableMark(self.name.."-round"), data.to.id)
    end
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, "#joy__ziqu-invoke::"..data.to.id)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local mark = player:getTableMark(self.name.."-round")
    table.insert(mark, data.to.id)
    room:setPlayerMark(player, self.name.."-round", mark)
    room:doIndicate(player.id, {data.to.id})
    if not data.to:isNude() then
      local ids = table.filter(data.to:getCardIds("he"), function(id)
        return table.every(data.to:getCardIds("he"), function(id2)
          return Fk:getCardById(id).number >= Fk:getCardById(id2).number end) end)
      local card = room:askForCard(data.to, 1, 1, true, self.name, false, ".|.|.|.|.|.|"..table.concat(ids, ","), "#joy__ziqu-give:"..player.id)
      if #card > 0 then
        card = card[1]
      else
        card = table.random(ids)
      end
      room:obtainCard(player.id, card, true, fk.ReasonGive)
    end
    return true
  end
}
local diaoling = fk.CreateActiveSkill{
  name = "joy__diaoling",
  anim_type = "control",
  min_card_num = 1,
  target_num = 1,
  prompt = "#joy__diaoling",
  card_filter = function (self, to_select, selected)
    return Fk:getCardById(to_select):getMark("@@joy__mubing-inhand") > 0
  end,
  target_filter = function(self,to_select,selected)
    return #selected == 0 and to_select ~= Self.id
  end,
  on_use = function(self, room, effect)
    local room = Self.room
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    local cards = effect.cards
    room:obtainCard(target,cards,false,fk.ReasonGive,player.id,self.name)
    if player.dead then return end
    local n = #cards - 1
    local  gets = {}

    for _, cid in ipairs(cards) do
      local c =  Fk:getCardById(cid)
      if #gets == 0 then
        table.insertIfNeed(gets,cid)
      else
        local gets2 = table.simpleClone(gets)
        for k, cid2 in pairs(gets2) do
          local c2 = Fk:getCardById(cid2)
          if c.number < c2.number then
            table.insert(gets,k,cid)
          elseif c.number == c2.number then
            return 
          end
        end
        if not table.contains(gets,cid) then
          table.insert(gets,#gets + 1,cid)
        end
      end
    end
    if #gets > 0 then
      local num 
      for k, cid in ipairs(gets) do
        if k == 1 then
          num = Fk:getCardById(cid).number
        else
          num = num + 1
          if Fk:getCardById(cid).number ~= num then
            return
          end
        end
      end
    end
    if  n > 0 and not player.dead then
      local targets = room:askForChoosePlayers(player,table.map(table.filter(room:getOtherPlayers(player), function(p)
        return not p:isNude() end), Util.IdMapper),1,n,"#joy__diaoling-get:::"..n,self.name,true)
      if #targets > 0 then
        for _, pid in ipairs(targets) do
          if player.dead then return end
          local p = room:getPlayerById(pid)
          local card = room:askForCardChosen(player,p,"he",self.name)
          if card ~= nil then
            room:obtainCard(player,card,false,fk.ReasonPrey)
          end
        end
      end
    end
  end,
}
zhangliao:addSkill(mubing)
zhangliao:addSkill(ziqu)
zhangliao:addSkill(diaoling)
Fk:loadTranslationTable{
  ["joysp__zhangliao"] = "张辽",
  ["#joysp__zhangliao"] = "功果显名",

  ["joy__mubing"] = "募兵",
  [":joy__mubing"] = "出牌阶段限一次，你可以亮出牌堆顶四张牌，然后你可以弃置任意张手牌，获得任意张亮出的牌，你弃置牌点数之和不能小于获得牌点数之和。",
  ["joy__ziqu"] = "资取",
  [":joy__ziqu"] = "每名角色每轮限一次，当你对其他角色造成伤害时，你可以防止此伤害，令其交给你一张点数最大的牌。",
  ["joy__diaoling"] = "调令",
  [":joy__diaoling"] = "出牌阶段，你可以将任意张“募兵”牌交给一名其他角色，若以此法给出的牌点数连续且各不相同，你可以获得场上至多X名角色各一张牌（X为给出的“募兵”牌数-1）。",
  ["joy__mubing_prey"] = "募兵",
  ["#joy__mubing-prompt"] = "募兵：选择你要获得和弃置的牌",
  ["joy__mubing_to_prey"] = "获得",
  ["joy__mubing_to_throw"] = "弃置",
  ["#joy__mubing-discard"] = "募兵：你可以弃置任意张手牌，获得点数之和不大于你弃牌点数之和的牌",
  ["@joy__mubing"] = "募兵",
  ["#joy__ziqu-invoke"] = "资取：是否防止对 %dest 造成的伤害，改为令其交给你一张点数最大的牌？",
  ["#joy__ziqu-give"] = "资取：你需要交给 %src 一张点数最大的牌",
  ["@@joy__mubing-inhand"] = "募兵",
  ["#joy__diaoling"] = "资取：你可以将任意张“募兵”牌交给一名其他角色。",
  ["#joy__diaoling-get"] = "资取：你可以选择至多%arg名角色获得其各一张牌。",

  ["$mubing1"] = "兵者，不唯在精，亦在广。",
	["$mubing2"] = "男儿当从军，功名马上取。",
  ["$ziqu1"] = "留财不留命，留命不留财。",
  ["$ziqu2"] = "兵马已动，尔等速将粮草缴来。",
  ["$diaoling1"] = "邻军告急，当遣将急援。",
  ["$diaoling2"] = "兵甲已足，当汇集三军。",
  ["~sp__zhangliao"] = "孤军难鸣，进退维谷。",
}

local diaochan = General(extension, "joysp__diaochan", "qun", 3, 3, General.Female)
local lihun = fk.CreateActiveSkill{
  name = "joy__lihun",
  mute = true,
  target_num = 1,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = function(self, to_select, selected)
    return #selected == 0 
  end,
  target_filter = function(self, to_select, selected, cards)
    local target = Fk:currentRoom():getPlayerById(to_select)
    return #selected == 0 and
    not target:isKongcheng() and to_select ~= Self.id
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    player:broadcastSkillInvoke(self.name, 1)
    room:notifySkillInvoked(player, self.name, "control")
    local mark = player:getMark("joy__lihun-phase")
    if mark == 0 then mark = {} end
    table.insertIfNeed(mark, target.id)
    room:setPlayerMark(player, "joy__lihun-phase", mark)
    player:turnOver()
    if player.dead or target.dead or target:isKongcheng() then return end
    local dummy = Fk:cloneCard("dilu")
    dummy:addSubcards(target:getCardIds("h"))
    room:moveCardTo(dummy, Card.PlayerHand, player, fk.ReasonPrey, self.name, nil, false, player.id)
  end,
}
local lihun_record = fk.CreateTriggerSkill{
  name = "#joy__lihun_record",
  mute = true,
  events = {fk.EventPhaseEnd},
  can_trigger = function(self, event, target, player, data)
    return target == player and player.phase == Player.Play and player:getMark("joy__lihun-phase") ~= 0
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke("joy__lihun", 2)
    room:notifySkillInvoked(player, "joy__lihun", "control")
    local mark = player:getMark("joy__lihun-phase")
    for _, id in ipairs(mark) do
      if player.dead or player:isNude() then return end
      local to = room:getPlayerById(id)
      if not to.dead then
        local cards = player:getCardIds("he")
        local n = to.hp
        if n < #cards then
          cards = room:askForCard(player, n, n, true, "joy__lihun", false, ".", "#lihun-give::"..to.id..":"..n)
        end
        room:moveCardTo(cards, Card.PlayerHand, to, fk.ReasonGive, "joy__lihun", nil, false, player.id)
      end
    end
  end,
}
local biyue = fk.CreateTriggerSkill{
  name = "joysp__biyue",
  anim_type = "drawcard",
  events = {fk.TurnEnd},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) 
  end,
  on_use = function(self, event, target, player, data)
    local n = 1
    if not player.faceup then
      n = 3
    end
    player:drawCards(n, self.name)
  end,
}
lihun:addRelatedSkill(lihun_record)
diaochan:addSkill(lihun)
diaochan:addSkill(biyue)
Fk:loadTranslationTable{
  ["joysp__diaochan"] = "貂蝉",
  ["#joysp__diaochan"] = "暗黑的傀儡师",

  ["joy__lihun"] = "离魂",
  [":joy__lihun"] = "出牌阶段限一次，你可翻面，并获得一名其他角色所有手牌。"..
  "出牌阶段结束时，你交给该角色X张牌（X为其体力值）。",
  ["joysp__biyue"] = "闭月",
  [":joysp__biyue"] = "回合结束阶段开始时，你可以摸一张牌，如你处于翻面状态，则摸三张牌。",
  ["joy__lihun_record"] = "离魂",

}


local zhaoyun = General(extension, "joysp__zhaoyun", "qun", 3)
zhaoyun:addSkill("longdan")
zhaoyun:addSkill("chongzhen")
Fk:loadTranslationTable{
  ["joysp__zhaoyun"] = "赵云",
  ["#joysp__zhaoyun"] = "白马先锋",
}

local sp__zhenji = General(extension, "joysp__zhenji", "qun", 3, 3, General.Female)
local joy__jinghong = fk.CreateTriggerSkill{
  name = "joy__jinghong",
  anim_type = "control",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self.name) and player.phase == Player.Start and
      table.find(player.room:getOtherPlayers(player), function(p) return not p:isKongcheng() end)
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = table.map(table.filter(room:getOtherPlayers(player), function(p)
      return not p:isKongcheng() end), function(p) return p.id end)
    local n = math.min(#room.alive_players - 1, 4)
    local tos = room:askForChoosePlayers(player, targets, 1, n, "#joy__jinghong-choose:::"..n, self.name, true)
    if #tos > 0 then
      self.cost_data = tos
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    for _, id in ipairs(self.cost_data) do
      if player.dead then return end
      local p = room:getPlayerById(id)
      if not p.dead and not p:isKongcheng() then
        local card = table.random(p:getCardIds("h"))
        p:showCards(card)
        if Fk:getCardById(card).color == Card.Black and (room:getCardOwner(card) == p or room:getCardArea(card) == Card.DiscardPile) then
          room:obtainCard(player, card, true, fk.ReasonPrey)
          if room:getCardOwner(card) == player and room:getCardArea(card) == Card.PlayerHand then
            room:setCardMark(Fk:getCardById(card), "@@joy__jinghong-inhand", 1)
          end
        elseif Fk:getCardById(card).color == Card.Red and room:getCardOwner(card) == p and room:getCardArea(card) == Card.PlayerHand then
          room:throwCard({card}, self.name, p, p)
        end
      end
    end
  end,

  refresh_events = {fk.TurnEnd},
  can_refresh = function(self, event, target, player, data)
    return target == player and player:usedSkillTimes(self.name, Player.HistoryTurn) > 0
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    for _, id in ipairs(player:getCardIds("h")) do
      room:setCardMark(Fk:getCardById(id), "@@joy__jinghong-inhand", 0)
    end
  end,
}
local joy__jinghong_maxcards = fk.CreateMaxCardsSkill{
  name = "#joy__jinghong_maxcards",
  exclude_from = function(self, player, card)
    return card:getMark("@@joy__jinghong-inhand") > 0
  end,
}
local joy__luoshen = fk.CreateViewAsSkill{
  name = "joy__luoshen",
  anim_type = "defensive",
  pattern = "jink",
  card_filter = function(self, to_select, selected)
    return #selected == 0 and Fk:getCardById(to_select).color == Card.Black
  end,
  view_as = function(self, cards)
    if #cards ~= 1 then return end
    local card = Fk:cloneCard("jink")
    card.skillName = self.name
    card:addSubcard(cards[1])
    return card
  end,
}
local nya__luoshen_trigger = fk.CreateTriggerSkill{
  name = "#nya__luoshen_trigger",
  mute = true,
  events = {fk.CardUsing, fk.CardResponding},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill("joy__luoshen") and table.contains(data.card.skillNames, "joy__luoshen") and
      player:usedSkillTimes(self.name, Player.HistoryRound) == 0
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, "joy__luoshen")
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local cards = {}
    while true do
      local judge = {
        who = player,
        reason = "joy__luoshen",
        pattern = ".|.|spade,club",
        skipDrop = true,
      }
      room:judge(judge)
      table.insert(cards, judge.card)
      if judge.card.color ~= Card.Black or not room:askForSkillInvoke(player, "joy__luoshen") then
        break
      end
    end
    cards = table.filter(cards, function(card) return room:getCardArea(card.id) == Card.Processing end)
    if #cards == 0 then return end
    local dummy = Fk:cloneCard("dilu")
    dummy:addSubcards(table.map(cards, function(card) return card:getEffectiveId() end))
    room:obtainCard(player.id, dummy, true, fk.ReasonJustMove)
  end,
}
joy__jinghong:addRelatedSkill(joy__jinghong_maxcards)
joy__luoshen:addRelatedSkill(nya__luoshen_trigger)
sp__zhenji:addSkill(joy__jinghong)
sp__zhenji:addSkill(joy__luoshen)
Fk:loadTranslationTable{
  ["joysp__zhenji"] = "甄姬",
  ["joy__jinghong"] = "惊鸿",
  [":joy__jinghong"] = "准备阶段，你可以选择至多X名其他角色（X为存活角色数-1，至多为4），依次随机展示其一张手牌，若为：黑色，你获得之，"..
  "且本回合不计入手牌上限；红色，其弃置之。",
  ["joy__luoshen"] = "洛神",
  [":joy__luoshen"] = "你可以将一张黑色牌当【闪】使用或打出；每轮限一次，你以此法使用或打出【闪】时，你可以判定，若结果为：黑色，你获得之，"..
  "然后你可以重复此流程；红色，你获得之。",
  ["#joy__jinghong-choose"] = "惊鸿：令至多%arg名其他角色依次随机展示一张手牌，若为黑色你获得之，若为红色其弃置之",
  ["@@joy__jinghong-inhand"] = "惊鸿",
}

return extension
